/**
 * 1314. 矩阵区域和
 */

class Solution6 {
    public int[][] matrixBlockSum(int[][] mat, int k) {
        int n = mat.length, m = mat[0].length;
        int[][] answer = new int[n][m], dp = new int[n + 1][m + 1];

        // 初始化dp表，dp[i][j] 表示[1,1]~[i][j]的面积之和
        for(int i = 1; i <= n; i++) {
            for(int j = 1; j <= m; j++) {
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1] + mat[i - 1][j - 1];
            }
        }

        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                // 求[x1,y1]、[x2,y2]坐标
                int x1 = Math.max(0, i -k) + 1, y1 = Math.max(0, j - k) + 1;
                int x2 = Math.min(n - 1, i + k) + 1, y2 = Math.min(m - 1, j + k) + 1;
                answer[i][j] = dp[x2][y2] - dp[x1 - 1][y2] - dp[x2][y1 - 1] + dp[x1 - 1][y1 - 1];
            }
        }

        return answer;
    }
}